<template>
  <div>
    <div class="seckill">
      <el-button
        :disabled="isDisabled"
        :style="{ backgroundColor: isDisabled ? '#d3d3d3' : '#409eff' }"
        @click="handleSeckill"
      >
        {{ isDisabled ? `秒杀中... ${countdown}秒` : "立即秒杀" }}
      </el-button>
    </div>
    <div>产品列表</div>
    <div v-for="item in goodslist" :key="item.id">
      商品名称: {{ item.name }} <br />
      价格: {{ item.price }} <br />
      <el-button type="primary" @click="toJoin(item)">加入购物车</el-button>
      <hr />
    </div>
  </div>
</template>

<!--vue 组件选项定义-->
<script setup>
import { ref, onBeforeMount, onUnmounted } from "vue";
import { queryProduct, addToCar } from "@/api/product.js";
import { ElMessage } from "element-plus";
const goodslist = ref([]);

//加入购物车
async function toJoin(goods) {
  goods.num = 1;
  let res = await addToCar(goods);
  if (res.code == 200) {
    ElMessage({
      message: "加入成功",
      type: "success"
    });
  }
}

async function init() {
  let res = await queryProduct({
    page: 1,
    pageSize: 10
  });

  console.log("res>>", res);

  if (res.code == 200) {
    goodslist.value = res.data.list;
  }
}

// 秒杀相关参数
const countdown = ref(30);
const isDisabled = ref(true);
let timer = null;
// 防抖函数
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 秒杀处理函数
const handleSeckill = debounce(() => {
  console.log("执行秒杀操作");
  // 在这里添加秒杀逻辑
}, 1000);

// 启动倒计时
function startCountdown() {
  isDisabled.value = true;
  countdown.value = 30;

  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isDisabled.value = false;
    }
  }, 1000);
}
// 清理定时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
});

onBeforeMount(() => {
  init();
  startCountdown(); // 启动倒计时
});
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.seckill {
  margin-top: 20px;
}
</style>
